import axios from 'axios';
class Request {
    constructor(baseUrl) {
        this.baseUrl = baseUrl;
        // 根据后台返回码判断，处理
        this.codeHander = {
            "417": () => {
                this.toLogin();
            },
            "1000": () => {
                this.toLogout();
            },
            "1033": () => {
                this.toLogin()
            }
        }
    }

    // login 登录
    toLogin() {

    }

    // logout 退出
    toLogout() {

    }
    // check code 检查请求状态
    checkStatus(code = 200, msg) {
        const codeHander = this.codeHander;
        if (codeHander.hasOwnProoerty(code)) {
            codeHander[code];
        }

        if (code !== 200) {
            window.alert(msg);
        }
    }


    mergeHeader(headers) {
        const commonHeaders = {
            ...this.headers,
            ...headers,
            from: 'PC_WEB_APP'
        }

        return commonHeaders
    }
    // post method request
    post(url, payload, headers) {
        const _this = this;
        return new Promise((resolve, reject) => {
            axios({
                url: `${_this.baseUrl}${url}`,
                method: 'POST',
                data: payload,
                header: _this.mergeHeader(headers)
            }).then((res, error) => {
                _this.checkStatus(res.data);
                if (error) {
                    reject(error);
                    return;
                }
                
                resolve(res);
            })
        })
    }
    // get method request
    get(url, payload, headers) {
        const _this = this;
        return new Promise((resolve, reject) => {
            axios({
                method: 'GET',
                url: `${_this.baseUrl}${url}`,
                data: payload,
                header: _this.mergeHeader(headers)
            }).then((res, error) => {
                _this.checkStatus(res.data);
                if (error) {
                    reject(error);
                    return;
                }
                resolve(res);
            })
        })
    }
}

export default Request;